package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.arlen.photo.photopickup.presenter.PhotoPresenter;
import com.arlen.photo.photopickup.util.MediaUtils;
import com.arlen.photo.photopickup.view.ImageLookActivity;
import com.arlen.photo.photopickup.view.PhotoPickupActivity;
import com.arlen.photo.photopickup.widget.SimpleGrid;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.customView.LoadingWaitDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.emojiUtils.EmotionMainFragment;
import com.wbao.dianniu.listener.IAskListener;
import com.wbao.dianniu.logical.Const;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.update.AmDataChangeManager;
import com.wbao.dianniu.manager.AskManager;
import com.wbao.dianniu.utils.ActivityUtils;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 匿名提问
 *
 * @author yejianjun
 */
public class AmQuestionActivity extends AppCompatActivity implements OnClickListener, IAskListener {

    private final int ANONY_TYPE = 2;
    private ImageButton cancel;
    private Button submit;
    private EditText mEditText;
    private AskManager manager;
    private Dialog pDialog;
    private TextView contentLength;
    private SimpleGrid mSimpleGrid;
    private PhotoPresenter mPhotoPresenter;
    private boolean isClick = false;
    private ImageView picImage;
    private ImageView aFriendIV;
    private CheckBox mCheckBox;
    private LocationClient mLocationClient = null;
    private BDLocationListener myListener = new MyLocationListener();

    private ImageView emojiBtn;
    private ScrollView mInfoRL;
    private EmotionMainFragment emotionMainFragment;
    private int REQ_CODE = 600;
    private Map<Integer, String> noticeJson = new HashMap<Integer, String>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityUtils.setStatusBarColor(this);
        setContentView(R.layout.activity_am_question);
        mPhotoPresenter = new PhotoPresenter(this, "goods");
        initview();
        manager = new AskManager(this);
        manager.addAskListener(this);
        // 初始化定位信息
        initLocation();
        initEmotionMainFragment();
    }

    /**
     * 初始化表情面板
     */
    public void initEmotionMainFragment() {
        //构建传递参数
        Bundle bundle = new Bundle();
        //绑定主内容编辑框
        bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT, false);
        //隐藏控件
        bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN, true);
        //替换fragment
        //创建修改实例
        emotionMainFragment = EmotionMainFragment.newInstance(EmotionMainFragment.class, bundle);
        emotionMainFragment.bindToContentView(mInfoRL, emojiBtn, mEditText);
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_emotionview_main, emotionMainFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();
    }

    private void initview() {
        ((TextView) findViewById(R.id.ask_title)).setText(getResources().getString(R.string.anonymous_title));
        cancel = findViewById(R.id.ask_back_button);
        submit = findViewById(R.id.ask_submit);
        mCheckBox = findViewById(R.id.am_release_checkbox);

        mEditText = findViewById(R.id.am_editText);
        mEditText.addTextChangedListener(watcher);
        contentLength = findViewById(R.id.Content_length);
        cancel.setOnClickListener(this);
        submit.setOnClickListener(new NoDoubleClickListener() {

            @Override
            public void onNoDoubleClick(View v) {
                // TODO Auto-generated method stub
                String content;
                content = mEditText.getText().toString().trim();
                if (TextUtils.isEmpty(content)) {
                    Notification.showToastMsg(AmQuestionActivity.this, "内容不能为空");
                    return;
                }
                if (mPhotoPresenter.isUploading()) {
                    Notification.showToastMsg(AmQuestionActivity.this, getResources().getString(R.string.picture_uploading));
                    return;
                }
                if (!isClick) {
                    isClick = true;
                    pDialog = LoadingWaitDialog.createLoadingDialog(AmQuestionActivity.this, "");
                    pDialog.show();
                    // 把图片列表转化成string
                    String questImgs = listToString(mPhotoPresenter.getSelectedList(), ',');
                    int showAliasName = mCheckBox.isChecked() == true ? 1 : 0;
                    // 去重noticeJson
                    String noticeJ = Utils.toHeavyNoticeJson(noticeJson, mEditText.getText().toString());
                    //
                    int anonymous = 0;
                    if (mCheckBox.isChecked()) {
                        anonymous = 1;
                    } else {
                        anonymous = 0;
                    }
                    manager.ask(GlobalContext.getAccountId(), ANONY_TYPE, replaceLineBlanks(content), questImgs, showAliasName, GlobalContext.address, noticeJ, anonymous);
                }
            }
        });

        mSimpleGrid = findViewById(R.id.img_grid);
        mPhotoPresenter.initView(mSimpleGrid);
        mSimpleGrid.setMaxItemPerRow(3);
        mSimpleGrid.setItemMarginHor(5f);
        mSimpleGrid.setItemMarginVer(5f);
        mPhotoPresenter.updateImgGrid();


        mCheckBox = findViewById(R.id.am_release_checkbox);
        // 根据用户状态 判断匿名是否可点击
        if (GlobalContext.getPerfectData()) {
            mCheckBox.setClickable(true);
        } else {
            mCheckBox.setChecked(true);
            mCheckBox.setClickable(false);
            mCheckBox.setButtonDrawable(R.drawable.xq_checkbox_unpress_ok);
        }

        picImage = findViewById(R.id.bar_image_chose_pic);
        picImage.setOnClickListener(this);
//        picImage.setVisibility(View.INVISIBLE);
        aFriendIV = findViewById(R.id.bar_image_a_friends);
        aFriendIV.setOnClickListener(this);

        mInfoRL = findViewById(R.id.am_question_rl);
        emojiBtn = findViewById(R.id.bar_image_add_btn);

    }

    @Override
    public void onBackPressed() {
        /**
         * 判断是否拦截返回键操作
         */
        if (!emotionMainFragment.isInterceptBackPress()) {
            // 注释这段代码 这个会双击才能退出
            //super.onBackPressed();
            finish();
        }
    }

    TextWatcher watcher = new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            contentLength.setText(s.length() + "/150");
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0) {
                // 清空输入内容时，清除@效果的hashMap
                mEditText.setHint(getResources().getString(R.string.qa_detail_hint));
                if (null != noticeJson) {
                    noticeJson.clear();
                }
            }
        }
    };

    private void initLocation() {
        // 定位初始化
        mLocationClient = new LocationClient(this);
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        // 需要地址信息，设置为其他任何值（string类型，且不能为null）时，都表示无地址信息。
        option.setIsNeedAddress(true);
        option.setScanSpan(1000);
        // 当gps可用，而且获取了定位结果时，不再发起网络请求，直接返回给用户坐标。这个选项适合希望得到准确坐标位置的用户。如果gps不可用，再发起网络请求，进行定位。
        option.setPriority(LocationClientOption.GpsFirst);
        mLocationClient.setLocOption(option);
        mLocationClient.start();
    }

    /**
     * 实现实位回调监听
     */
    private class MyLocationListener implements BDLocationListener {

        public MyLocationListener() {
        }

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null) {
                return;
            }
            if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                GlobalContext.address = location.getCity();
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                GlobalContext.address = location.getCity();
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                GlobalContext.address = location.getCity();
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeServerError) {
//				locationTV.setText("网络不通，定位失败");
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                mLocationClient.stop();
            } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
//				locationTV.setText("无法获取有效定位，定位失败");
                mLocationClient.stop();
            }

        }

//        @Override
//        public void onConnectHotSpotMessage(String s, int i) {
//
//        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ask_back_button:
                if (TextUtils.isEmpty(mEditText.getText().toString())) {
                    finish();
                } else {
                    CustomDialog.Builder builder = new CustomDialog.Builder(this);
                    builder.setTitle("确认退出发布吗？");
                    builder.setPositiveButton(getResources().getString(R.string.confirm),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });
                    builder.setNegativeButton(getResources().getString(R.string.cancel),
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    builder.create().show();
                }
                break;
            case R.id.bar_image_chose_pic:
                mPhotoPresenter.choseImage();
                break;
            case R.id.bar_image_a_friends:
                Intent aIntent = new Intent();
                aIntent.setClass(AmQuestionActivity.this, SelectFriendActivity.class);
                startActivityForResult(aIntent, REQ_CODE);
                break;
            default:
                break;
        }
    }

    private String listToString(ArrayList<MediaUtils.ImageProperty> list, char separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                sb.append(list.get(i).desc);
            } else {
                sb.append(list.get(i).desc);
                sb.append(separator);
            }
        }
        return sb.toString();
    }

    @Override
    public void onAskFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        isClick = false;
    }

    @Override
    public void onAskSuccess(QaResponse addData) {
        // TODO Auto-generated method stub
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        isClick = false;
        AmDataChangeManager amDataChangeManager = AmDataChangeManager.getInstance();
        addData.isOwnSend = true;
        amDataChangeManager.addOneDataNotify(addData);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PhotoPickupActivity.REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                if (PhotoPickupActivity.getSelectedImgPros(data) != null) {
                    mPhotoPresenter.pickPhotoResult(data);
                }
            }
        } else if (requestCode == ImageLookActivity.REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                if (data != null) {
                    mPhotoPresenter.lookImageResult(data);
                }
            }
        } else if (requestCode == REQ_CODE) {
            if (resultCode == RESULT_OK) {
                String userName = data.getStringExtra(Const.INTENT_NICENAME);
                int friendId = data.getIntExtra(Const.BUNDLE_ACCOUNTID, 0);
                if (userName != null && 0 != friendId) {
                    noticeJson.put(friendId, userName);// 加入noticeJson
                    // 光标出插入@
                    int index = mEditText.getSelectionStart();
                    Editable editable = mEditText.getText();
                    editable.insert(index, "@" + userName);
                }
            }
        }
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if (null != manager) {
            manager.removeAskListener(this);
        }
        // 移除绑定的EditText
        if (null != emotionMainFragment) {
            emotionMainFragment.removeEditText();
        }
    }

    private String replaceLineBlanks(String str) {
        String result = "";
        if (str != null) {
            Pattern p = Pattern.compile("(\n(\\s*?\n)+)");
            Matcher m = p.matcher(str);
            result = m.replaceAll("\n\n");
        }
        return result;
    }

}
